﻿using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using System.Web.Mvc;
using Autofac;
using Pay.Core;
using Pay.DTO;
using Pay.IService;
using Pay.TO;

namespace Pay.Web.Areas.Admin.Controllers {
	[RouteArea("admin")]
	[RoutePrefix("transfer")]
	public class TransferController : AdminController {
		private ITransferService _iTransferService;
		private IMerchantService _iMerchantService;
		private IComponentContext _iocContext;

		public TransferController(IComponentContext iocContext, IMerchantService iMerchantService, ITransferService iTransferService) {
			_iocContext = iocContext;
			_iMerchantService = iMerchantService;
			_iTransferService = iTransferService;
		}

		public ActionResult Index() {
			return View();
		}

		public JsonResult Gets(TransferQuery query) {
			var model = _iTransferService.Get(query);
			var amt = query.pay_channel != PayChannel.None ? _iTransferService.TransferAmount(query.pay_channel) : 0;
			var result = new { transfer_amount = amt, model.page, model.rows, model.size, model.total_pages, model.total_result };
			return Json(ResultToJson.Json(result), JsonRequestBehavior.AllowGet);
		}

		public JsonResult Get(long id) {
			var model = _iTransferService.Get(id);
			return Json(ResultToJson.Json(model), JsonRequestBehavior.AllowGet);
		}

		public JsonResult GetBatchs(TransferBatchQuery query) {
			var model = _iTransferService.Get(query);
			return Json(ResultToJson.Json(model), JsonRequestBehavior.AllowGet);
		}

		public async Task<JsonResult> ApplyBatch(TransferQuery query) {
			if (query.pay_channel == PayChannel.None)
				return Json(ResultToJson.Json<string>("通道没有选择"), JsonRequestBehavior.AllowGet);
			if (query.merchant_id == 0)
				return Json(ResultToJson.Json<string>("O商没有选择"), JsonRequestBehavior.AllowGet);

			batch_transfer model = new batch_transfer { pay_channel = query.pay_channel, merchant_id = query.merchant_id };
			var list = _iTransferService.Get(query);
			var rows = list.rows;
			for (int i = 2; i <= list.total_pages; i++) {
				query.page = i;
				list = _iTransferService.Get(query);
				rows.AddRange(list.rows);
			}
			foreach (var row in rows) {
				if (row.status == TransferStatus.Apply)
					model.orders.Add(new transfer_item_model {
						order_no = row.order_no, account_name = row.account_name, account_no = row.account_no, bank_name = row.bank_name,
						id_card = row.id_card, tran_amount = ((int)(row.transfer_amount * 100)).ToString(), busi_type = row.busi_type
					});
			}
			if (model.orders.Count == 0)
				return Json(ResultToJson.Json<string>("没有提现申请"), JsonRequestBehavior.AllowGet);
			var iPayService = _iocContext.ResolveKeyed<IPayService>(query.pay_channel);
			var result = await iPayService.Transfer(model);
			if (result.status == 1)
				return Json(result, JsonRequestBehavior.AllowGet);
			return Json(ResultToJson.Json<string>("报盘失败"), JsonRequestBehavior.AllowGet);
		}

		/// <summary>
		/// T1额度查询
		/// </summary>
		/// <returns>The balance.</returns>
		/// <param name="pay_channel">Pay channel.</param>
		public async Task<JsonResult> Balance(PayChannel pay_channel) {
			if (pay_channel == PayChannel.None)
				return Json(ResultToJson.Json<string>("通道没有选择"), JsonRequestBehavior.AllowGet);

			var iPayService = _iocContext.ResolveKeyed<IPayService>(pay_channel);
			var result = await iPayService.Quota("", "1");
			return Json(result, JsonRequestBehavior.AllowGet);
		}

		/// <summary>
		/// 下载高清文件
		/// </summary>
		/// <returns>The out pay.</returns>
		/// <param name="file">File.</param>
		public FileResult DownloadOutPay(string file) {
			var fileName = IOHelper.GetMapPath("OutPay", file.Substring(0, 8), file);
			//FileStream fs = new FileStream(fileName, FileMode.Open);
			//byte[] bytes = new byte[(int)fs.Length];
			//fs.Read(bytes, 0, bytes.Length);
			//fs.Close();
			//Response.Charset = "UTF-8";
			//Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
			//Response.ContentType = "application/octet-stream";
			//Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(file));
			//Response.BinaryWrite(bytes);
			//Response.Flush();
			//Response.End();
			//return new EmptyResult();
			return File(new FileStream(fileName, FileMode.Open), "application/octet-stream", Server.UrlEncode(file));
		}

		/// <summary>
		/// 报盘
		/// </summary>
		/// <returns>The notify.</returns>
		/// <param name="dto">Dto.</param>
		public async Task<JsonResult> BatchNotify(transfer_batch_dto dto) {
			var iPayService = _iocContext.ResolveKeyed<IPayService>(dto.pay_channel);
			var result = await iPayService.TransferNotify(dto.id, dto.batch_file, dto.merchant_id);
			if (result > 0)
				return Json(ResultToJson.Json("报盘成功", result), JsonRequestBehavior.AllowGet);
			return Json(ResultToJson.Json<string>("报盘失败"), JsonRequestBehavior.AllowGet);
		}

		/// <summary>
		/// 回盘
		/// </summary>
		/// <returns>The back.</returns>
		/// <param name="dto">Dto.</param>
		public async Task<JsonResult> BatchBack(transfer_batch_dto dto) {
			var iPayService = _iocContext.ResolveKeyed<IPayService>(dto.pay_channel);
			var result = await iPayService.TransferBack(dto.id, dto.notice_tran_no, dto.merchant_id);
			if (result > 0)
				return Json(ResultToJson.Json("回盘成功", result), JsonRequestBehavior.AllowGet);
			return Json(ResultToJson.Json<string>("回盘失败"), JsonRequestBehavior.AllowGet);
		}

		/// <summary>
		/// 单条代付查询
		/// </summary>
		/// <returns>The first.</returns>
		/// <param name="merchant_no">O单商商户号</param>
		/// <param name="order_no">Order no.</param>
		/// <param name="pay_channel">Pay channel.</param>
		[Route("transfer_first")]
		public async Task<JsonResult> TransferFirst(string merchant_no, string order_no, PayChannel pay_channel) {
			var iPayService = _iocContext.ResolveKeyed<IPayService>(pay_channel);
			var query = new transfer_query { merchant_no = merchant_no, method = "6001", order_no = order_no, pay_channel = pay_channel };
			var result = await iPayService.TransferQuery(query);
			if (result.result_code == 1000) {
				if (result.status == 1)
					return Json(ResultToJson.Json("提现成功", ""), JsonRequestBehavior.AllowGet);
				return Json(ResultToJson.Json<string>(result.result_msg), JsonRequestBehavior.AllowGet);
			}
			return Json(ResultToJson.Json<string>(result.result_msg), JsonRequestBehavior.AllowGet);
		}

		/// <summary>
		/// 重新走代付，需要流程上先做查询，查询没有后再技术确定才可以做此操作
		/// </summary>
		/// <returns>The payoff.</returns>
		/// <param name="id">Identifier.</param>
		/// <param name="pay_channel">Pay channel.</param>
		public async Task<JsonResult> Payoff(long id, PayChannel pay_channel) {
			var iPayService = _iocContext.ResolveKeyed<IPayService>(pay_channel);
			var result = await iPayService.ReTransfer(id);
			if (result.result_code == 1000) {
				if (result.status == 1)
					return Json(ResultToJson.Json("下发成功", ""), JsonRequestBehavior.AllowGet);
				return Json(ResultToJson.Json<string>(result.result_msg), JsonRequestBehavior.AllowGet);
			}
			return Json(ResultToJson.Json<string>(result.result_msg), JsonRequestBehavior.AllowGet);
		}

		/// <summary>
		/// 取消
		/// </summary>
		/// <returns>The cancel.</returns>
		/// <param name="id">Identifier.</param>
		public JsonResult Cancel(long id) {
			var result = _iTransferService.Cancel(id);
			if (result > 0) {
				return Json(ResultToJson.Json("取消成功"), JsonRequestBehavior.AllowGet);
			}
			return Json(ResultToJson.Json<string>("取消失败"), JsonRequestBehavior.AllowGet);
		}
	}
}